const Router = require('koa-router')

let router = new Router()
router.prefix('/user')

router.get('/', async ctx => {
	let res = await ctx.db.query('SELECT * FROM users')
	ctx.body = res
})
// 注册
router.post('/do-register', async ctx => {
	// 1 用户名密码
	let {
		username,
		password,
		email
	} = ctx.request.fields;
	// 判断用户名是否存在
	let res = await ctx.db.query('select * from users where username=?', [username]);
	if (res.length !== 0) {
		ctx.body = {
			code: 0,
			mes: '用户名已经存在'
		}
		return;
	}
	// 插入数据
	let dbres = await ctx.db.query('insert into users (username, password ,email) values (?,?,?)', [username, password,
		email
	]);

	if (dbres.affectedRows != 1) {
		ctx.body = {
			code: '01',
			mes: '添加失败'
		};
		return;
	}
	ctx.body = {
		code: '01',
		mes: '插入成功'
	};

})

// 登录
router.post('/do-login', async ctx => {
	// 1 用户名密码
	let {
		username,
		password
	} = ctx.request.fields;
	console.log(username, password)
	// 查询username是否存在
	let res = await ctx.db.query('select * from users where username=?', [username]);
// 	
	if (res.length === 0) {
		ctx.body = {
			code: 0,
			mes: '用户不存在'
		}
		return
	}
	let user = res[0];
 
	console.log(user.password === password)
	if (user.password == password) {
		ctx.body = {
			code: 1,			 
			mes: '登录成功'
		}
		// 挂在session用户认证判断
		ctx.session.user = user; 
		return
	}
	ctx.body = {
		code: 0,
		mes: '用户名或密码错误'
	}



})





router.post('/new', async ctx => {

	// let res = await ctx.db.query('SELECT * FROM baidunews')
	console.log(1)
	ctx.request.fields // 包含全部请求信息是对象
	ctx.request.files // 包含全部文件信息是数组
	ctx.body = 'we'

})
module.exports = router.routes()
